const { formatTime } = require('../../utils/util.js')
const { getApiUrl } = require('../../config/config.js')
const app = getApp()
Page({
  data: {
    userId: null,
    messageList: [],
    loading: false,
    theme: 'light'
  },

  onLoad() {
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo) {
      this.setData({ userId: userInfo.id })
      this.loadMessageList()
    }
  },


  onShow() {
    if (this.data.userId) {
      this.loadMessageList()
    }
  },

  onPullDownRefresh() {
    this.loadMessageList()
  },

  loadMessageList() {
    const userId = this.data.userId
    if (!userId) return

    this.setData({ loading: true })
    
    wx.request({
      url: getApiUrl('/message/list'),
      method: 'GET',
      data: { userId },
      success: (res) => {
        if (res.data.code === 200) {
          const latestMessages = new Map()

          // 遍历所有消息，只保留每个会话的最新消息
          res.data.data.forEach(message => {
            const currentMessageTime = new Date(message.createdAt).getTime()
            const existingMessage = latestMessages.get(message.conversationId)
            
            if (!existingMessage || 
                currentMessageTime > new Date(existingMessage.createdAt).getTime()) {
              latestMessages.set(message.conversationId, message)
            }
          })

          // 格式化消息列表
          const formattedMessages = []
          latestMessages.forEach(message => {

            const isFromMe = message.senderId === userId
            console.log(isFromMe)
            
            // 确定对话对方的信息
            let otherUserName, otherUserAvatar
            if (isFromMe) {
              console.log(message)
              // 我发送的消息，对方是接收者
              otherUserName = message.receiverName || '未知用户'
              otherUserAvatar = message.receiverAvatar || '/images/avatar/default.png'
            } else {
              // 我收到的消息，对方是发送者
              otherUserName = message.senderName || '未知用户'
              otherUserAvatar = message.senderAvatar || '/images/avatar/default.png'
            }

            formattedMessages.push({
              id: message.id,
              otherUserId: isFromMe ? message.receiverId : message.senderId,
              name: otherUserName,
              avatar: otherUserAvatar,
              lastMessage: isFromMe ? `我：${message.content}` : message.content,
              time: formatTime(new Date(message.createdAt)),
              createdAt: message.createdAt
            })
            console.log(formattedMessages)
          })

          // 按时间倒序排序
          formattedMessages.sort((a, b) => 
            new Date(b.createdAt) - new Date(a.createdAt)
          )

          this.setData({
            messageList: formattedMessages,
            loading: false
          })
        }
      },
      fail: (error) => {
        console.error('Failed to load messages:', error)
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        })
      },
      complete: () => {
        this.setData({ loading: false })
        wx.stopPullDownRefresh()
      }
    })
  },

  onTapMessage(e) {
    const { id } = e.currentTarget.dataset
    const message = this.data.messageList.find(msg => msg.id === id)
    
    if (message) {
      wx.navigateTo({
        url: `../chat/chat?targetUserId=${message.otherUserId}&targetName=${encodeURIComponent(message.name || '未知用户')}`
      })
    }
  },
  
  // 导航到赞和收藏页面
  navigateToLoveAndCollect() {
    wx.navigateTo({
      url: '../loveAndCollect/loveAndCollect'
    })
  },

  // 导航到新增关注页面
  navigateToNewFollow() {
    wx.navigateTo({
      url: '../newFollow/newFollow'
    })
  },
  
  // 导航到评论和@页面
  navigateToCommentForMe() {
    wx.navigateTo({
      url: '../commentForMe/commentForMe'
    })
  }
}) 